<?php
namespace App\Http\Controllers\V1;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Helpers\Utils;
use App\Helpers\RestUtils;
use App\Helpers\Http\HttpCurl;
use App\Helpers\RestResponseFactory;
use App\Models\Orm\VipNews;
use App\Models\Orm\Product;
use App\Models\Orm\Welfare;
use App\Models\Orm\Majiahao;
use App\Models\Orm\Advertsing;
use App\Models\Orm\ProductMajiahao;
use App\Models\Orm\VersionMajiahao;
use App\Models\Orm\DataProductApply;
use App\Models\Factory\UserFactory;
use App\Models\Factory\IdentityFactory;

/**
 * 马甲号
 * Class MhomeController
 * @package App\Http\Controllers\V2
 */
class MhomeController extends Controller
{

    /**
     * 根据马甲号编号名称和市场编号获取相应上线状态
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public static function getStatus(Request $request)
    {  

        // 声明马甲号名称和市场
        $name = $request ->input('name','');
        $market = $request ->input('market','');
        $result = Majiahao::where(['name'=>$name, 'market'=>$market, 'status'=>1])->first();
        // 声明上线状态默认为0（下线）
        $response['status'] = 0;
        if($result){
            $response['status'] = 1;
        }
        return RestResponseFactory::ok($response);

    }

    /**
     * 根据马甲号编号名称和市场编号更改上线状态或添加马甲号
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public static function saveStatus(Request $request)
    { 

        // 声明马甲号名称和市场编号和上线状态
        $name = $request ->input('name','');
        $market = $request ->input('market','');
        $status = $request ->input('status', 1);
        if(empty($name)){
            return RestResponseFactory::ok(RestUtils::getStdObj(),RestUtils::getErrorMessage(1000), 1000, RestUtils::getErrorMessage(1000));
        }

        $mjhObj = Majiahao::where(['name'=>$name, 'market'=>$market])->first();
        if(empty($mjhObj)){
            // 添加马甲号
            $mjhObj = new Majiahao();
            $mjhObj->name = $name;
            $mjhObj->market = $market;
            $mjhObj->created_at = date('Y-m-d H:i:s');
        }
        // 更新相应马甲号上线状态和更新时间
        $mjhObj->updated_at = date('Y-m-d H:i:s');
        $mjhObj->status = intval($status);

        if($mjhObj->save()){
            return RestResponseFactory::ok();
        }

        return RestResponseFactory::ok(RestUtils::getStdObj(),RestUtils::getErrorMessage(1605), 1605, RestUtils::getErrorMessage(1605));


    }



    /**
     * 首页banner列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public static function banner(Request $request)
    {   
        // 查询广告数据
        $banner = Advertsing::select('advername','pictrue','app')
                                ->where(['status'=>1])
                                ->orderBy('sroting')
                                ->get()->toArray();
        return RestResponseFactory::ok($banner);
    }


    /**
     * 消息列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function news(Request $request)
    {

        $news = VipNews::select('body')
                            ->where('status',1)
                            ->where('type',2)
                            ->orderBy('sort')
                            ->get()->toArray();

        return RestResponseFactory::ok($news);

    }


    /**
     * 产品列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public static function product(Request $request)
    { 
        // 声明马甲号名称
        $name = $request ->input('name');
        $offset = intval($request ->input('offset', 0));
        $number = intval($request ->input('number', 10));

        // 获取产品列表数据
        $product = Product::with('labels')
                            ->join('product_delivery_url', 'product.id', '=', 'product_delivery_url.product_id')
                            ->select(['product.id', 'product.pname','product_delivery_url.url','product.product_logo', 'product.product_introduction', 'min_algorithm', 'fastest_time', 'minimum_amount', 'maximum_amount', 'interest_algorithm'])
                            ->where(['product.status'=>1, 'product.vip_level'=>0, 'product_delivery_url.type'=>1])
                            ->offset($offset)
                            ->limit($number)
                            ->orderBy('product.id','desc')
                            ->get()
                            ->toArray();
        // 产品信息格式化
        $product = self::productFormat($product, $name);

        
        return RestResponseFactory::ok($product);

    }

    /**
     * 热门产品列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public static function hotProduct(Request $request)
    { 
        // 声明马甲号名称
        $name = $request ->input('name');

        //热门产品查询
        $recommend = Product::with('labels')
                            ->join('product_delivery_url', 'product.id', '=', 'product_delivery_url.product_id')
                            ->join('recommend','product.id', '=', 'recommend.product_id')
                            ->select(['product.id', 'product.pname','product_delivery_url.url','product.product_logo', 'product.product_introduction', 'min_algorithm', 'fastest_time', 'minimum_amount', 'maximum_amount', 'interest_algorithm'])
                            ->where(['product.status'=>1, 'product.vip_level'=>0, 'product_delivery_url.type'=>1])
                            ->orderBy('product.id','desc')
                            ->get()
                            ->toArray();
        // 获取热门产品id，避免重复查询
        $recommendArr = array_column($recommend, 'id');

        // 新上线产品
        $online = Product::with('labels')
                            ->join('product_delivery_url', 'product.id', '=', 'product_delivery_url.product_id')
                            ->select(['product.id', 'product.pname','product_delivery_url.url','product.product_logo', 'product.product_introduction', 'min_algorithm', 'fastest_time', 'minimum_amount', 'maximum_amount', 'interest_algorithm'])
                            ->where(['product.status'=>1, 'product.online'=>1, 'product.vip_level'=>0, 'product_delivery_url.type'=>1])
                            ->whereNotIn('product.id', $recommendArr)
                            ->orderBy('product.id','desc')
                            ->get()
                            ->toArray();

        $product = array_merge($recommend, $online);
        // 产品信息格式化
        $product = self::productFormat($product, $name);

        return RestResponseFactory::ok($product);

    }

    /**
     * 申请top产品列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public static function topProduct(Request $request)
    { 
        // 声明马甲号名称
        $name = $request ->input('name');

        //热门产品查询
        $recommend = Product::with('labels')
                            ->join('product_delivery_url', 'product.id', '=', 'product_delivery_url.product_id')
                            ->join('recommend','product.id', '=', 'recommend.product_id')
                            ->select(['product.id', 'product.pname','product_delivery_url.url','product.product_logo', 'product.product_introduction', 'min_algorithm', 'fastest_time', 'minimum_amount', 'maximum_amount', 'interest_algorithm'])
                            ->where(['product.status'=>1, 'product.vip_level'=>0, 'product_delivery_url.type'=>1])
                            ->orderBy('product.id','desc')
                            ->get()
                            ->toArray();
        // 获取热门产品id，避免重复查询
        $recommendArr = array_column($recommend, 'id');

        // 新上线产品
        $online = Product::with('labels')
                            ->join('product_delivery_url', 'product.id', '=', 'product_delivery_url.product_id')
                            ->select(['product.id', 'product.pname','product_delivery_url.url','product.product_logo', 'product.product_introduction', 'min_algorithm', 'fastest_time', 'minimum_amount', 'maximum_amount', 'interest_algorithm'])
                            ->where(['product.status'=>1, 'product.online'=>1, 'product.vip_level'=>0, 'product_delivery_url.type'=>1])
                            ->whereNotIn('product.id', $recommendArr)
                            ->orderBy('product.id','desc')
                            ->get()
                            ->toArray();

        $product = array_merge($recommend, $online);
        // 产品信息格式化
        $product = self::productFormat($product, $name);

        // 将产品按申请点击排行
        $fieldArr = array();
        foreach ($product as $k => $v) {
            $fieldArr[$k] = str_replace('万', '', $v['apply']);
        }
        array_multisort($fieldArr, SORT_DESC, $product);

        return RestResponseFactory::ok($product);

    }

    /**
     * 产品列表筛选
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public static function screening(Request $request)
    { 

        // 声明马甲号名称
        $name = $request ->input('name');
        $offset = intval($request ->input('offset', 0));
        $number = intval($request ->input('number', 10));
        // 身份筛选条件(1 上班族 2 其他 3 逍遥客 4 企业主)
        $identity = $request ->input('identity');

        //产品筛选
        $product = Product::with('labels')
                            ->join('product_delivery_url', 'product.id', '=', 'product_delivery_url.product_id')
                            ->select(['product.id', 'product.pname','product_delivery_url.url','product.product_logo', 'product.product_introduction', 'min_algorithm', 'fastest_time', 'minimum_amount', 'maximum_amount', 'interest_algorithm'])
                            ->where(['product.status'=>1, 'product.vip_level'=>0, 'product_delivery_url.type'=>1])                            
                            ->where('crowd', 'like', '%' . $identity . '%')
                            ->offset($offset)
                            ->limit($number)
                            ->orderBy('product.id','desc')
                            ->get()
                            ->toArray();                            
        // 产品信息格式化
        $product = self::productFormat($product, $name);
        
        return RestResponseFactory::ok($product);


    }

    /**
     * 产品信息格式化(添加申请次数和马甲号配置)
     * @param  $product array  产品信息
     * @param  $name    string 马甲号名称
     * @return $product array  格式化产品信息
     */
    public static function productFormat($product, $name)
    {
        foreach ($product as $key => $value) {

             // 添加产品申请次数
             $apply = DataProductApply::where('platform_product_id',$value['id'])->count()+20000;             
             $product[$key]['apply'] = round($apply/100, 1).'万';

             // 查询产品马甲号配置中是否已配置当前产品
             $productMajiahao = ProductMajiahao::select('p_name','p_logo','p_desc')
                                                ->where(['m_name'=>$name, 'p_id'=>$product[$key]['id']])
                                                ->first();
             $product[$key]['p_name'] = $productMajiahao->p_name ?? $product[$key]['pname'];
             $product[$key]['p_logo'] = $productMajiahao->p_logo ?? $product[$key]['product_logo'];
             $product[$key]['p_desc'] = $productMajiahao->p_desc ?? $product[$key]['product_introduction'];
             unset($product[$key]['pname'],$product[$key]['product_logo'],$product[$key]['product_introduction']);
        }
        return $product;
    }


    /**
     * 福利列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public static function welfare(Request $request)
    {
        // 查询马甲号福利列表数据
        $welfare = Welfare::select(['name', 'image', 'link'])
                            ->orderby('id', 'desc')
                            ->where(['status' => 1, 'is_mjh'=>1])
                            ->get()
                            ->toArray();

        return RestResponseFactory::ok($welfare);

    }



    /**
     * 马甲号版本升级
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function version(Request $request){

        // 马甲号名称
        $name    = $request ->input('name');
        $versioncode = $request ->input('version');
        //获取版本信息
        $version = VersionMajiahao::where(['name'=>$name])
                                    ->orderBy('id', 'desc')
                                    ->limit(1)
                                    ->first();

        if($version){
            if($versioncode < $version['versioncode']){

                //是否忽略安装
                $data['isIgnorable'] = ($version['is_ignorable'] == 1) ? true : false;

                //是否强制安装
                $data['isForce'] = ($version['is_force'] == 1) ? true : false;

                //是否自动下载安装
                $data['isAutoInstall'] = ($version['is_auto_install'] == 1) ? true : false;

                $data['maxtimes'] = $version['maxtimes'];
                $data['size'] = $version['size'];
                $data['versioncode'] = $version['versioncode'];
                $data['versionname'] = $version['versionname'];
                $data['updatecontent'] = $version['updatecontent'];
                $data['url'] = $version['url'];
                $data['md5'] = $version['md5'];
                return RestResponseFactory::ok($data);
            }

        }

        return RestResponseFactory::ok(RestUtils::getStdObj());


    }

}